// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package service_cmd

import (
	"context"
	"encoding/base64"
	"fmt"
	"strings"

	"gitcode.com/opendragonfly/df_server/dao/config_dao"
	"github.com/dgraph-io/badger/v4"
	"go.opentelemetry.io/collector/component"
)

var AuthComponentId = component.MustNewID("auth")

type AuthComponent struct{}

func (c *AuthComponent) Start(ctx context.Context, host component.Host) error {
	return nil
}

func (c *AuthComponent) Shutdown(ctx context.Context) error {
	return nil
}

func (c *AuthComponent) Authenticate(ctx context.Context, sources map[string][]string) (context.Context, error) {
	enable, err := config_dao.StateDao.Get()
	if err != nil {
		if err == badger.ErrKeyNotFound {
			enable = true
		} else {
			return nil, err
		}
	}
	if !enable {
		return ctx, nil
	}
	auth := sources["authorization"]
	if len(auth) == 0 {
		return nil, fmt.Errorf("miss authorization")
	}
	if !strings.HasPrefix(auth[0], "Basic ") {
		return nil, fmt.Errorf("not basic auth")
	}
	basicStr, err := base64.StdEncoding.DecodeString(auth[0][6:])
	if err != nil {
		return nil, err
	}
	index := strings.Index(string(basicStr), ":")
	if index == -1 {
		return nil, fmt.Errorf("wrong basic auth")
	}
	username := string(basicStr[:index])
	password := string(basicStr[index+1:])

	secret, err := config_dao.SecretDao.Get(username)
	if err != nil {
		return nil, err
	}
	if password == secret.Password {
		return ctx, nil
	}
	return nil, fmt.Errorf("wrong basic auth secret")
}

type myHost struct{}

func (nh *myHost) ReportFatalError(_ error) {}

func (nh *myHost) GetExtensions() map[component.ID]component.Component {
	return map[component.ID]component.Component{
		AuthComponentId: &AuthComponent{},
	}
}
